<!--用户个人中心页面-->
<template>

  <div style="padding:0;display: flex;height: 100vh;background-color: #e4e4e4;
    background-image: url(https://s1.hdslb.com/bfs/static/stone-free/dyn-home/assets/bg.png@1c.avif)">
<!-- 左侧用户信息卡片   -->
    <div class="user-left">
      <div style=" display: grid;place-items: center;">
        <el-image
            :src="BASE_URL+user.imgUrl"
            fit="cover"
            style="width: 50px; height: 50px; border-radius: 50%;">
        </el-image>
      </div>

      <p style="text-align: center">{{ user.username }}</p>

      <p style="  overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 4; /* 控制显示的最大行数 */-webkit-box-orient: vertical;
                  width: 100%;
                  white-space: pre-line;color: #666666;font-weight: bolder">
        {{ user.profile }}</p>

      <el-button style="border-color: #3C82F5;color: #3C82F5;"
                 @click="editUser">
        修改个人资料
      </el-button>
      <el-divider/>

      <div>
        <div class="info-item">
          <el-icon>
            <School/>
          </el-icon>
          <span class="label">学校:</span>
          <span class="filler"></span>
          <span class="content">{{ user.schoolName }}</span>
        </div>
        <div class="info-item">
          <el-icon>
            <Clock/>
          </el-icon>
          <span class="label">加入:</span>
          <span class="filler"></span>
          <span class="content">{{ user.createTime.split(" ")[0] }}</span>
        </div>
      </div>
<!--   此处设置弹窗   -->
      <!-- 编辑用户弹窗 -->
      <!-- :before-close="handleClose"
      在关闭之前调用handleClose方法,避免点击窗口外部也能关弹窗  -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible"
                 :before-close="handleClose"
                 style="width: 1000px;padding:40px;">
        <el-form label-position="top" label-width="80px">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="用户名">
                <el-input placeholder="请输入用户名" v-model="saveUserForm.username"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄">
                <el-input placeholder="请输入年龄" v-model="saveUserForm.age"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="性别">
                <el-radio-group v-model="saveUserForm.gender">
                  <el-radio label="男" border value="男" style="margin: 0;"></el-radio>
                  <el-radio label="女" border value="女"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号">
                <el-input placeholder="请输入手机号" v-model="saveUserForm.phone"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="学校">
                <el-input placeholder="请输入学校" v-model="saveUserForm.schoolName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱">
                <el-input placeholder="请输入邮箱" v-model="saveUserForm.email"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="头像">
                <el-upload
                    v-model:file-list="fileList"
                    v-model:action="actionUrl"
                    name="file"
                    limit="1"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-success="handleUploadSuccess"
                >
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </el-upload>
                <el-dialog v-model="imgDialogVisible">
                  <img w-full :src="dialogImageUrl"/>
                </el-dialog>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="城市">
                <el-input placeholder="请输入学校城市" v-model="saveUserForm.city"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveUser">保存</el-button>
        </template>
      </el-dialog>
    </div>
<!--  此处为右方卡片  -->
    <div class="user-right">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="发帖" name="first">
          <!--   此处存放帖子内容       -->
          <el-card class="card" v-for="blogArr in blogArr" :key="blogArr.id" style=" margin-bottom: 20px;">
            <template #header>
              <div>
                <el-button type="text" link>{{ blogArr.title }}</el-button>
              </div>
            </template>
            <p class="text item">{{ blogArr.content }}</p>
            <!-- 如果有其他卡片内容，请继续在此处添加 -->
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="评论" name="second">Config</el-tab-pane>
        <el-tab-pane label="点赞" name="third">Role</el-tab-pane>
      </el-tabs>
    </div>
    <el-button @click="router.push('/home')">返回</el-button>
  </div>
</template>
<script setup>

import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";
import router from "@/router";
//控制弹窗是否出现
const dialogVisible = ref(false);
const dialogTitle = ref('修改个人信息');
// 定义默认激活的标签页
const activeName = ref('first');
//定义数组保存帖子内容
const blogArr = ref({id: '', username: '', title: '', content: '', imgUrl: '', type: '', createTime: ''});
//定义对象收集新增/修改用户弹窗的表单信息
const saveUserForm = ref({username: '', age: '', gender: '', imgUrl: '', phone: '', email: '', schoolName: '', city:''});
//加载当前登录用户的信息
const user = ref(getUser());
//定义数组保存搜索框内容
const searchBlogForm = ref({
  username: '',
  title: ''
});

//编辑用户
const editUser=()=>{
  //打开弹窗并修改标题
  dialogVisible.value = true;
  dialogTitle.value = '编辑用户';
  //给后端发请求:根据员工id查指定员工的信息
  axios.get(BASE_URL+'/v1/user/select?id='+user.value.id).then((response)=>{
    if(response.data.code == 2000) {
      //注意:后端返回的是List<UserVO> list! 所以这里是data[0]
      console.log(response.data.data[0]);
      saveUserForm.value = response.data.data[0];
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
//处理弹窗关闭的方法
const handleClose = () => {
  if (confirm('确定关闭本窗口吗?')) {
    //用户确认关闭后,关闭弹窗
    dialogVisible.value = false;
    //清空已输入的表单数据
    saveUserForm.value = {};
    fileList.value=[];
  }
}
//定义保存用户的方法
const saveUser = () => {
  let data = qs.stringify(saveUserForm.value);
  axios.post(BASE_URL + '/v1/user/save', data)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('保存成功!');
          dialogVisible.value = false;//关闭弹窗
          saveUserForm.value = {};//清空已入库的表单数据，否则再次打开弹窗还是之前的值
          //新增/更新用户后,都需要重新加载用户数据
          fileList.value=[];
          //查询更新后的用户数据，将其存入localStorage中，并刷新页面
          axios.get(BASE_URL+'/v1/user/select?id='+user.value.id).then((response)=>{
            if(response.data.code == 2000) {
              localStorage.setItem('user',JSON.stringify(response.data.data[0]));
              router.go(0);
            }else{
              ElMessage.error(response.data.msg);
            }
          })
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}
//定义加载帖子的方法
const loadBlog = () => {
  let data = qs.stringify(searchBlogForm.value);
  axios.get(BASE_URL + '/v1/blog/select?' + data).then((response) => {
    if (response.data.code == 2000) {

      blogArr.value = response.data.data;
      console.log(response.data.data);
    } else {
      ElMessage.error(response.data.msg);
    }
  })
};
// 一进页面自动加载数据
onMounted(() => {
  loadBlog();
});

/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const imgDialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
  console.log(uploadFile);
  // console.log(fileList.value[0].response.data);
}

// 新增处理图片上传成功的函数
const handleUploadSuccess = (response) => {
  if (response.data) {
    // 假设前端可以通过特定基础路径访问图片
    const imageUrl = `${response.data}`;
    saveUserForm.value.imgUrl = imageUrl;
  } else {
    ElMessage.error('图片上传成功，但未获取到图片URL！');
    console.error('Invalid response structure for uploaded image.', response);
  }
};
</script>


<style scoped>
.user-left {
  width: 300px;
  padding: 10px;
  height: 400px;
  background-color: #fff;
  margin: 15px 50px 0 10px;
}

.user-right {
  padding: 10px;
  width: 60%;

  background-color: #fff;
  margin: 15px 50px 0 10px;
  display: flex;
  flex-direction: column; /* 使卡片垂直排列 */
  gap: 20px; /* 卡片间的间隔 */
  overflow-y: auto;

}

.info-item {
  display: flex;
  align-items: center;
}

.filler {
  flex-grow: 1; /* 填充剩余空间 */
}

</style>